import React, { memo, useEffect, useState } from 'react'
import { RightWrapper } from './style'
import IconGlobal from '@/assets/svg/icon_global'
import IconMenu from '@/assets/svg/icon_menu'
import IconAvatar from '@/assets/svg/icon_avatar'
import { useNavigate } from 'react-router-dom'

const HeaderRight = memo(() => {
  // 控制profile panel的显示
  const [showPanel, setShowPanel] = useState(false)
  const navigate = useNavigate()
  // 挂载生命周期监听鼠标点击  
  useEffect(() => {
    // 鼠标点击 设置panel面板隐藏
    function listenerHandler(){
      setShowPanel(false)
    }
    // 添加鼠标点击事件监听
    window.addEventListener('click', listenerHandler)
    // 卸载生命周期取消监听鼠标点击
    return () => window.removeEventListener("click", listenerHandler)
  }, [])
  // 点击导航栏右边profile图标
  function showProfilePanel(e){
    // 如果当前点击的是导航栏右边profile图标 就阻止冒泡不让window执行回掉（window只控制其他位置的点击事件）
    e.stopPropagation()
    setShowPanel(!showPanel)
  }
  function toLoginPage() {
    navigate('/login')
  }
  return (
    <RightWrapper>
      <div className='btns'>
        <span className='btn' onClick={toLoginPage}>登录</span>
        <span className='btn'>注册</span>
        <span className='btn'>
          <IconGlobal/>
        </span>
      </div>
      <div className='profile' onClick={showProfilePanel}>
        <IconMenu/>
        <IconAvatar/>
        {
          showPanel && (
            <div className='panel'>
            <div className='top'>
              <div className='item'>注册</div>
              <div className='item'>登录</div>
            </div>
            <div className='bottom'>
              <div className='item'>出租房源</div>
              <div className='item'>开展体验</div>
              <div className='item'>帮助</div>
            </div>
          </div>
          )
        }
      </div>

    </RightWrapper>
  )
})

export default HeaderRight